import shutil
from pathlib import Path

import fire


def check_dir_status(root):
    ready = True
    if root.is_dir():
        if len(list(root.iterdir())) > 0:
            print("Project root is not empty.")
            ready = False
    return ready


def build_project_structure(root):
    root.mkdir(parents=True, exist_ok=True)
    # root directories
    for name in ["configs", "docs", "resources", "scripts", "src", "test", "tools"]:
        (root / name).mkdir()
    # sub directories
    (root / "resources/datasets").mkdir()
    (root / "tools/aux").mkdir()
    for name in ["component", "data", "data_prepare", "model", "utils"]:
        (root / "src" / name).mkdir()
    (root / "src/data_prepare/sub_datasets").mkdir()
    return


def build_base_files(root):
    # README.md
    (root / "README.md").touch()
    # requirements.txt
    with (root / "requirements.txt").open("w", encoding="utf-8") as f:
        for lib_name in ["easydict", "fire", "PyYAML"]:
            f.write(f"{lib_name}\n")
    return


def build(root, rebuild=False):
    root_path = Path(root)
    if rebuild:
        print("Clear and rebuild project. Enter to Confirm.")
        input()
        shutil.rmtree(root_path, ignore_errors=True)
    if check_dir_status(root_path):
        build_project_structure(root_path)
        build_base_files(root_path)
    return


if __name__ == "__main__":
    fire.Fire(build)
